package com.qk.management.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qk.common.PageResult;
import com.qk.common.constant.BusinessStatusConstants;
import com.qk.common.enums.ParamEnum;
import com.qk.common.exception.CommonException;
import com.qk.common.util.CurrentUserContextHolders;
import com.qk.dpmain.businesses.BusinessDo;
import com.qk.dto.business.BusinessDto;
import com.qk.dto.business.BusinessListDto;
import com.qk.dto.business.UpdateBusinessDto;
import com.qk.dto.HighSeas.HighSeasDto;
import com.qk.entity.Business;
import com.qk.entity.BusinessTrackRecord;
import com.qk.entity.Customer;
import com.qk.entity.User;
import com.qk.management.mapper.BusinessMapper;
import com.qk.management.mapper.BusinessTrackRecordMpper;
import com.qk.management.mapper.CustomerMapper;
import com.qk.management.mapper.UserMapper;
import com.qk.management.service.BusinessSercivce;
import com.qk.vo.business.BusinessesVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @文件名: BusinessSercivceImpl
 * @作者: DX
 * @创建日期: 2025/10/15
 * @描述:
 */
@Slf4j
@Service
@SuppressWarnings("all")
public class BusinessSercivceImpl extends ServiceImpl<BusinessMapper, Business> implements BusinessSercivce {

    @Autowired
    private BusinessMapper businessMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private BusinessTrackRecordMpper businessTrackRecordMpper;

    @Autowired
    private CustomerMapper customerMapper;

    @Override
    public PageResult<Business> highSeasList(HighSeasDto dto) {
        Page page = new Page<Business>(dto.getPage(), dto.getPageSize());
        Page<Business> list = this.businessMapper.selectHighSeasByPage(page,dto);
        return PageResult.<Business>builder()
                .total(Long.valueOf(list.getTotal()).intValue())
                .rows(list.getRecords())
                .build();
    }

    @Transactional
    @Override
    public void toCustomer(Integer id) {
        Business business = this.businessMapper.selectById(id);

        business.setStatus(BusinessStatusConstants.CONVERT_TO_BUSINESS);

        business.setUpdateTime(LocalDateTime.now());

        this.businessMapper.updateById( business);

        Customer customer = BeanUtil.copyProperties(business, Customer.class);

        customer.setId(null);

        customer.setBusinessId(business.getId());

        this.customerMapper.insert( customer);
    }

    @Transactional
    @Override
    public void updateBusinessById(UpdateBusinessDto dto) {
        Business business = BeanUtil.copyProperties(dto, Business.class);

        business.setUpdateTime(LocalDateTime.now());

        if (dto.getStatus() == BusinessStatusConstants.WAIT_FOLLOW_UP){
            business.setStatus(BusinessStatusConstants.FOLLOW_UP);
        }

        this.baseMapper.updateById(business);

        BusinessTrackRecord businessTrackRecord = BeanUtil.copyProperties(dto, BusinessTrackRecord.class);
        businessTrackRecord.setId(null);
        businessTrackRecord.setCreateTime(LocalDateTime.now());
        businessTrackRecord.setUserId(CurrentUserContextHolders.get());
        businessTrackRecord.setBusinessId(business.getId());
        this.businessTrackRecordMpper.insert(businessTrackRecord);
    }

    @Override
    public BusinessesVo getBusinessInfoById(Integer id) {
        Business business = this.businessMapper.selectById(id);

        Integer userId = business.getUserId();

        User byId = this.userMapper.getById(userId);

        List<BusinessTrackRecord> businessTrackRecords = this.businessTrackRecordMpper.selectList(Wrappers.lambdaQuery(BusinessTrackRecord.class)
                .in(BusinessTrackRecord::getBusinessId, id));

        BusinessesVo businessVo = BeanUtil.copyProperties(business, BusinessesVo.class);
        List<BusinessesVo.BusinessTrackRecordVo> list = businessTrackRecords.stream().map(item -> {
            BusinessesVo.BusinessTrackRecordVo vo = BeanUtil.copyProperties(item, BusinessesVo.BusinessTrackRecordVo.class);
            vo.setAssignName(byId.getName());
            return vo;
        }).toList();

        businessVo.setTrackRecords(list);
        return businessVo;
    }

    @Override
    public PageResult<BusinessDo> businesslist(BusinessListDto dto) {
        Page page = new Page<>(dto.getPage(), dto.getPageSize());
        Page<BusinessDo> list =this.baseMapper.selectByPage(page,dto);
        return PageResult.<BusinessDo>builder()
                .total(Long.valueOf(list.getTotal()).intValue())
                .rows(list.getRecords())
                .build();
    }

    @Override
    public void addBusiness(BusinessDto dto) {

        if (ObjectUtil.isEmpty(dto.getPhone()) || ObjectUtil.isEmpty(dto.getChannel())){
            log.error("手机号或渠道不能为空");
            CommonException.thowsCommonException(ParamEnum.PARAM_ENUM);
            return;
        }
        Business business = BeanUtil.copyProperties(dto, Business.class);
        business.setCreateTime(LocalDateTime.now());
        business.setUpdateTime(LocalDateTime.now());
        business.setStatus(BusinessStatusConstants.WAIT_ALLOCATION);
        this.baseMapper.insert( business);
    }
}
